<template>
    <div class="hc-video-component" :style="{width:(width+8+'px'), height:(!isFullScreen?(height+'px'):(100+'%'))}">
        <div class="hc-video-component__canvas-box" :style="(isFlash||(imgs.length===0))?'background:white;':'' ">
            <template v-for="(page,idx) in pages">
                <canvas
                        class="hc-video-component__canvas-context"
                        :key="idx"
                        :width="width"
                        :height="width*(297 / 210)"
                        :style="{background:`url('${(imgs.length>0&&imgs[idx]&&!isFlash)?imgs[idx]:''}')`,'background-size':'cover','padding':'0 1px',borderBottom:'1px solid #e3e3e3'}"
                        :id="'canvas'+memberId+'-'+page"
                        @click="stateChange"
                        @dblclick="fullScreen"
                ></canvas>
            </template>
        </div>
        <div class="hc-video-component__operation" :style="{opacity: (playSpeed.playSpeedSelect||pageSelect)?1:''}">
            <div class="hc-video-component__operation--left">

                <div style="width:50px;text-align: center;"
                     :class="!playState?'el-icon-caret-right':'iconfont icon-Group'"
                     @click="stateChange"></div>
                <div class="iconfont icon-shangyige" @click="$emit('previous')"></div>
                <div class="iconfont icon-next-chapter" @click="$emit('next')"></div>
            </div>
            <div class="hc-video-component__operation--progress">
                <div role="progressbar" class="el-progress el-progress--line">
                    <div class="el-progress-bar"
                         style="display: flex;flex-flow: row nowrap;justify-content: space-between;align-items: center;">
                        <div class="el-progress-bar__outer" style="flex:1;"
                             @click="clickProgress" @mousedown="mousedownProgress" @mouseup="mouseupProgress"
                             @mousemove="mousemoveProgress" @mouseleave="mouseupProgress">
                            <div class="el-progress-bar__inner"
                                 :style="{width: ((playTime/videoTime)*100).toFixed(2) + '%'}">
                                <div class="hc-video-component__operation--progress-point"></div>
                            </div>
                            <div class="el-progress-bar__inner"
                                 :style="{width: 100 + '%', backGroundColor:'rgba(0, 0, 0, 1)', opacity: 0.6}">
                            </div>
                        </div>
                        <div style="width:50px;font-size: 12px;padding: 10px;">
                            {{countMinutes(playTime,'mm:ss').desc }}/{{this.totalTime}}
                        </div>
                    </div>
                </div>
            </div>
            <div class="hc-video-component__operation--right">
                <el-popover
                        placement="top"
                        width="60"
                        v-model="playSpeed.playSpeedSelect"
                        transition="el-zoom-in-bottom"
                        popper-class="hc-video-component__speed-select">
                    <div class="hc-video-component__speed-select--options">
                        <div v-for="item in playSpeed.playSpeedArr" class="hc-video-component__speed-select--option"
                             @click="changePlaySpeed(item)">
                            {{playSpeed.playSpeedSelect?item.name:''}}
                        </div>
                    </div>
                    <div class="hc-video-component__speed-select--value" slot="reference">{{playSpeed.curSpeed.name}}
                    </div>
                </el-popover>
                <el-popover
                        placement="top"
                        width="60"
                        v-model="pageSelect"
                        transition="el-zoom-in-bottom"
                        popper-class="hc-video-component__speed-select">
                    <div class="hc-video-component__speed-select--options">
                        <div v-for="item in selectPages" class="hc-video-component__speed-select--option"
                             @click="changePage(item)" style="text-align: center;">
                            {{pageSelect?item.name:''}}
                        </div>
                    </div>
                    <div class="hc-video-component__speed-select--value iconfont icon-shangjiantou1" slot="reference">
                        {{curPage.name}}
                    </div>
                </el-popover>
                <div class="iconfont icon-quanping1" @click="fullScreen"></div>
            </div>
        </div>
    </div>
</template>

<script>
  require('../utils/FormatDate.js');
  import {Utils} from '../utils/Utils';
  import {CanvasConfig} from '../config/CanvasConfig';
  import $ from 'jquery';

  export default {
    name: "newVideo",
    props: {
      immediate: {
        type: Boolean,
        default: function () {
          return false;
        }
      },
      memberId: {
        type: [String, Number],
        default: function () {
          return '';
        }
      },
      pages: {
        type: Array,
        default: function () {
          return [];
        }
      },
      width: {
        type: [String, Number],
        default: function () {
          return 800;
        }
      },
      height: {
        type: [String, Number],
        default: function () {
          return (this.width ? this.width : 800) * (297 / 210);
        }
      },
      imgs: {
        type: Array,
        default: function () {
          return [];
        }
      },
      rawData: {
        default: function () {
          return '';
        }
      },
      isFlash: {
        type: Boolean,
        default: function () {
          return false
        }
      }
    },
    computed: {
      totalTime() {
        let temp = this.countMinutes(this.videoTime, 'hh:mm:ss').desc;
        console.log(temp, temp.indexOf('00:'));
        if (temp.indexOf('00:') === 0) {
          return temp.slice(3);
        } else {
          return temp;
        }
      },
      selectPages() {
        let temp = [];
        for (let i = 0, len = this.pages.length; i < len; i++) {
          temp.push({name: `第${i + 1}页`, value: i})
        }
        return temp;
      },
      writeData() {
        return Utils.handleAnswerData(this.rawData)
      },

      getNums() {
        return this.width / 210;
      },

      playTime() {
        let temp = Math.floor(
          (this.runTime * this.writeData.period) / 1000
        );
        if (temp > this.videoTime) {
          return this.videoTime;
        } else {
          return temp;
        }
      },

      boxScroll() {
        return document.getElementsByClassName('hc-video-component__canvas-box')[0];
      }
    },
    watch: {
      width: function () {
        //宽度变化以后表格需要重绘

        this.resetData();
      }
    },
    data() {
      return {
        curPage: {name: '第1页', value: 0},
        pageSelect: false,
        playProgress: 0,
        playSpeed: {
          curSpeed: {name: '1.0X', value: 1}, //默认5 就是正常速度
          playSpeedArr: [
            {name: '1.0X', value: 1},
            {name: '2.0X', value: 2},
            {name: '4.0X', value: 4},
            {name: '8.0X', value: 8},
            {name: '16.0X', value: 16},
            {name: '50.0X', value: 50},
            // {name: '100.0X', value: 100}
          ],
          playSpeedSelect: false
        },
        timeDrawLast: null,
        videoTime: 0,
        runTime: 0,
        playState: 0,
        timer: null,
        totalPage: 0,
        lastScroll: 0,
        dragStatus: false,
        stateChanged: false,
        isFullScreen: false,
        flashList: []
      }
    },
    created() {
      this.resetData();
      if (this.immediate) {
        setTimeout(() => {
          this.stateChange();
        }, 500);
      }
    },
    beforeDestroy() {
      clearTimeout(this.timer);
    },
    methods: {
      fullScreen(e) {
        e.preventDefault();
        e.stopPropagation();
        if (!this.isFullScreen) {
          document.getElementsByClassName("hc-video-component")[0].webkitRequestFullScreen();
        } else {
          document.webkitCancelFullScreen();
        }
        this.isFullScreen = !this.isFullScreen;
      },
      mousemoveProgress(e) {
        e.preventDefault();
        e.stopPropagation();
        if (this.dragStatus) {
          this.clearBoard(true);
          for (let ele of e.path) {
            if (ele.className === 'el-progress-bar__outer') {
              this.runTime = Math.floor(((this.videoTime) * 10) * (((e.layerX / ele.clientWidth) <= 1) ? (e.layerX / ele.clientWidth) : 1));
              break;
            }
          }
          this.drawOnTime();
          return false;
        } else {
          return false;
        }
      },
      mousedownProgress(e) {
        console.log('mousedown');
        e.preventDefault();
        e.stopPropagation();
        if (this.btnState === 1) {
          this.stateChange();
          this.stateChanged = true;
        }
        this.dragStatus = true;
        return false;
      },
      mouseupProgress(e) {
        console.log('mouseup');
        e.preventDefault();
        e.stopPropagation();
        if (this.dragStatus === true && this.stateChanged === true) {
          this.stateChange();
          this.stateChanged = false;
        }
        this.dragStatus = false;
        return false;
      },
      clickProgress(e) {
        console.log('click');
        e.preventDefault();
        e.stopPropagation();
        this.clearBoard(true);
        for (let ele of e.path) {
          if (ele.className === 'el-progress-bar__outer') {
            this.runTime = Math.floor(((this.videoTime) * 10) * (((e.layerX / ele.clientWidth) <= 1)
              ? (e.layerX / ele.clientWidth) : 1));
            break;
          }
        }
        this.drawOnTime();
        return false;
      },
      countMinutes(time, fmt) {
        return Utils.countMinutes(time, fmt);
      },
      resetVideo() {
        this.playState = 0;
        this.drawPackge('', -1);
        this.runTime = 0;
        this.timeDrawLast = null;
        this.clearBoard();
      },
      stateChange() {
        if (!this.playState) {
          if (this.playTime >= this.videoTime) {
            this.resetVideo();
          }
          this.playState = 1;
          this.timeGo();
        } else {
          clearTimeout(this.timer);
          this.playState = 0;
        }
      },
      pauseVideo() {
        this.playState = 0;
        clearTimeout(this.timer);
      },
      changePlaySpeed(value) {
        this.playSpeed.playSpeedSelect = false;
        this.playSpeed.curSpeed = value;
      },

      changePage(value) {
        this.pageSelect = false;
        this.curPage = value;
        if (this.boxScroll.scrollTop < this.curPage.value * this.width * 297 / 210 || this.boxScroll.scrollTop > (this.curPage.value + 1) * this.width * 297 / 210)
          $(this.boxScroll).animate({scrollTop: this.curPage.value * this.width * 297 / 210}, 500);
        return false;
      },

      countFlash(canvasWidth, canvasHeight) {
        let flashList = {};
        for (let i = 0; i < this.totalPage; i++) {

          let pageInfo = this.pages[i];
          let cav = document.getElementById(`canvas${this.memberId}-${pageInfo}`).getContext('2d');
          let dots = this.writeData[pageInfo];
          if (!dots) {

            continue;
          }
          let top = 0,
            right = 0,
            left = canvasWidth,
            bottom = canvasHeight,
            flash = 1;
          for (let j in dots) {
            let timeDots = dots[j];
            for (let k = 0; k < timeDots.length; k++) {
              let dot = timeDots[k];
              let {x, y} = {x: dot.x, y: dot.y};
              if (y > top) top = y;
              if (y < bottom) bottom = y;
              if (x > right) right = x;
              if (x < left) left = x;
            }
          }
          let width = -left + right,
            height = top - bottom;
          flash = width / (canvasWidth * 0.9) > height / (canvasHeight * 0.9) ? width / (canvasWidth * 0.9) : height / (canvasHeight * 0.9);
          flash = flash > 0.11 && flash || 0.11;
          // flash *= this.getNums();
          // console.log(flash);
          cav.canvas.width = width / flash + 20;
          cav.canvas.height = height / flash + 20;
          flashList[pageInfo] = ({flash, left, bottom});
        }
        return flashList;
      },

      clearBoard(bool) {
        for (let i = 0; i < this.pages.length; i++) {
          let page = this.pages[i];
          //从0开始 清除笔画
          let canvas = document.getElementById(`canvas${this.memberId}-${page}`);
          let ctx = canvas.getContext('2d');

          ctx.clearRect(0, 0, Number(this.width), Number(this.width * 297 / 210));
          console.log(!bool);
          if (!bool) this.curPage = {name: '第1页', value: 0};
        }
      },

      resetData() {

        if (this.rawData) {
          this.$nextTick(() => {
            this.initConfig();
            this.clearBoard();
            this.resetVideo();

            if (this.isFlash) this.flashList = this.countFlash(this.width, this.height);
            this.drawAll();

          });
        }
      },

      timeGo() {
        if (this.playState === 1) {
          if (this.videoTime === 0) {
            this.$message({
              showClose: true,
              message: '当前无可播放内容哦',
              type: 'error'
            });
            return;
          }
          if (this.playTime >= this.videoTime) {
            this.pauseVideo();
            return;
          }

          if (this.runTime === 0) {
            this.clearBoard();
          }

          this.timer = setTimeout(() => {
            this.drawByTime(this.playTime);
            return this.timeGo();
          }, this.writeData.period / this.playSpeed.curSpeed.value);
          // console.log(this.writeData.period / this.playSpeed.curSpeed.value);
        }
      },

      initConfig() {
        this.totalPage = this.pages.length;
        this.videoTime = this.writeData.maxTime;
      },
      drawByTime: function () {
        //一 period 调用一次

        for (let i = 0, len = this.pages.length; i < len; i++) {
          let toDrawData = this.writeData[this.pages[i]];

          if (!toDrawData) {
            continue;
          }

          let temp = toDrawData[this.runTime];
          if (!temp || temp.length == 0) {
            continue;
          }
          this.curPage = this.selectPages[i];
          this.drawArr(temp, i);
        }
        this.runTime++;
      },

      drawOnTime: function () {

        for (let i = 0; i < this.pages.length; i++) {
          var toDrawData = this.writeData[this.pages[i]];
          if (!toDrawData) {
            continue;
          }
          for (let j = 0, len = Math.floor(this.runTime); j < len; j++) {
            let temp = toDrawData[j];
            if (!temp || temp.length === 0) {
              continue;
            }
            this.drawArr(temp, i);
          }
        }
      },

      drawArr(temp, pageIdx) {
        let canvas = document.getElementById(
          `canvas${this.memberId}-${this.pages[pageIdx]}`
        );
        let ctx;
        try {
          ctx = canvas.getContext('2d');
        } catch (e) {
          return
        }
        ctx.beginPath();
        ctx.lineWidth = CanvasConfig.lineWidth;
        let last = this.timeDrawLast;
        let dot, dotY, dotX;
        for (let i = 0, len = temp.length; i < len; i++) {
          dot = temp[i];
          dotY = dot.y * this.getNums;
          dotX = dot.x * this.getNums;
          if ((dotY + 297 * this.getNums * this.curPage.value - this.boxScroll.scrollTop) < 0 || (dotY + 297 * this.getNums * this.curPage.value - this.boxScroll.scrollTop) > this.boxScroll.clientHeight / 2) {
            this.lastScroll = dotY + 297 * this.getNums * this.curPage.value;
            if (!this.scrolling) {
              this.scrolling = true;
              setTimeout(() => {
                this.scrolling = false;
                $(this.boxScroll).animate({scrollTop: this.lastScroll - this.boxScroll.clientHeight / 2 + 100}, 500);
              }, 300)
            }
          }

          if (this.isFlash) {
            let flash = this.flashList[this.pages[pageIdx]].flash;
            let left = this.flashList[this.pages[pageIdx]].left;
            let bottom = this.flashList[this.pages[pageIdx]].bottom;

            if (last) {
              if (dot.idx != last.idx) {
                ctx.moveTo((last.x - left) / flash + 10, (last.y - bottom) / flash + 10);

              } else {


                ctx.moveTo((last.x - left) / flash + 10, (last.y - bottom) / flash + 10);
                ctx.lineTo((dot.x - left) / flash + 10, (dot.y - bottom) / flash + 10);
              }
            } else {

              ctx.moveTo((dot.x - left) / flash + 10, (dot.y - bottom) / flash + 10);
            }
          } else {

            if (last) {
              if (dot.idx != last.idx) {
                ctx.moveTo(last.x * this.getNums, last.y * this.getNums);

              } else {

                ctx.moveTo(last.x * this.getNums, last.y * this.getNums);
                ctx.lineTo(dotX, dotY);
              }
            } else {

              ctx.moveTo(dotX, dotY);
            }

          }
          last = dot;
        }
        ctx.stroke();
        ctx.closePath();
        this.timeDrawLast = last;

      },
      drawAll() {
        //一次将所有之前的轨迹画完

        this.drawPackge(this.writeData, true);
        this.drawPackge(this.writeData, false);
      },
      drawPackge: (() => {
        var lastDot = {};
        return function (data, isReset) {
          if (isReset) {
            lastDot = {};
            return;
          }

          let pages = this.pages;

          for (let i = 0; i < pages.length; i++) {
            //绘制所有点的数据
            let page = pages[i];
            let toDrawData = data[page];
            let canvas = document.getElementById(
              `canvas${this.memberId}-${page}`
            );
            let ctx = canvas.getContext('2d');
            ctx.lineWidth = CanvasConfig.lineWidth;
            ctx.beginPath();
            let dot, dotY, dotX;
            for (let key in toDrawData) {
              let temp = toDrawData[key];
              for (let j = 0, len = temp.length; j < len; j++) {
                dot = temp[j];
                dotY = dot.y * this.getNums;
                dotX = dot.x * this.getNums;
                if (this.isFlash) {
                  let flash = this.flashList[page].flash;
                  let left = this.flashList[page].left;
                  let bottom = this.flashList[page].bottom;

                  if (lastDot) {
                    if (dot.idx != lastDot.idx) {
                      ctx.moveTo((lastDot.x - left) / flash + 10, (lastDot.y - bottom) / flash + 10);

                    } else {


                      ctx.moveTo((lastDot.x - left) / flash + 10, (lastDot.y - bottom) / flash + 10);
                      ctx.lineTo((dot.x - left) / flash + 10, (dot.y - bottom) / flash + 10);
                    }
                  } else {

                    ctx.moveTo((dot.x - left) / flash + 10, (dot.y - bottom) / flash + 10);
                  }
                } else {

                  if (lastDot) {
                    if (dot.idx != lastDot.idx) {
                      ctx.moveTo(lastDot.x * this.getNums, lastDot.y * this.getNums);

                    } else {

                      ctx.moveTo(lastDot.x * this.getNums, lastDot.y * this.getNums);
                      ctx.lineTo(dotX, dotY);
                    }
                  } else {

                    ctx.moveTo(dotX, dotY);
                  }

                }
                lastDot = dot;
              }

            }
            ctx.stroke();
            ctx.closePath();
          }
        };
      })(),
    }
  }
</script>
